package com.chen.controller;


import com.chen.entity.R;
import com.chen.entity.User;
import com.chen.service.UserService;
import com.chen.utils.SMSUtils2;
import com.chen.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/sendMsg")
    public R sendMsg(@RequestBody User user, HttpSession session) {
        log.info(user.getPhone());
        String phone = user.getPhone();
        if (StringUtils.isNotBlank(phone)) {
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info(code);
            session.setAttribute(phone, code);
             SMSUtils2.sendMessage(phone, code);
            return R.success("验证码已经发送");
        }
        return R.error("服务异常,请稍后再试");
    }


    @PostMapping("/login")
    public R login(@RequestBody User user, HttpSession session) {
        String phone = user.getPhone();
        String code = user.getCode();
        Object vcode = session.getAttribute(phone);
        if (code.equals(vcode)) {
            User user1 = userService.findByPhone(phone);
            session.setAttribute("user",user1.getId());
            return R.success(user1);
        }
        return R.error("验证码错误");
    }
    @PostMapping("/loginout")
    public R logout(HttpSession session) {
        session.invalidate();
        return R.success(null);
    }
}
